<?php namespace App\Http\Controllers;

use App\Department;
use App\Doctors;
use App\DoctorTime;
use App\DoctorWeek;
use App\Exceptions\NotFoundException;
use App\FollowQrcode;
use App\Hospital;
use App\Orders;
use App\Packages;
use App\Questions;
use App\Referral;
use App\Services\Tools;
use App\Services\UserManager;
use App\User;
use App\UserInfo;
use App\UserXDoctor;
use Doctrine\DBAL\Driver\AbstractDriverException;
use EasyWeChat\Payment\Order;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
use PhpParser\Comment\Doc;

class DoctorController extends Controller
{
    public function userCenter(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=docUserCenter');
        }

        /** @var User $user */
        $userinfo = $user->doctorInfo;

        $appointAmount = Orders::whereDoctorId($user->id)->whereType('appoint')->whereIspay(1)->sum('order_price');
        $faceAmount = Orders::whereDoctorId($user->id)->whereType('face')->whereIspay(1)->sum('order_price');

        $patientCount = UserXDoctor::whereDoctorId($user->id)->count();

        return view('doctors.new-usercenter',['user'=>$user,'userinfo'=>$userinfo,'appoint_sum'=>$appointAmount,'face_sum'=>$faceAmount,'patientCount'=>$patientCount]);
    }

    public function userCenterSet(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=docUserCenter');
        }

        /** @var User $user */
        $userinfo = $user->doctorInfo;

        $hospitals = Hospital::all();

        if($userinfo){
            $allDep = Department::whereHospitalId($userinfo->hospital_id)->get();
        }else{
            $allDep = Department::whereHospitalId($hospitals[0]['id'])->get();
        }

        return view('doctors.new-usercenter-set',['user'=>$user,'userinfo'=>$userinfo,'hospitals'=>$hospitals,"deps"=>$allDep]);
    }

    public function setAppolitment(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=docUserCenter');
        }

        /** @var User $user */

//        $dateOne = DoctorTime::whereUserId($user->id)->whereType('appoint')->whereDays(date('Y-m-d',time()))->first();
//        $dateTwo = DoctorTime::whereUserId($user->id)->whereType('appoint')->whereDays(date('Y-m-d',strtotime('+1 days')))->first();
//        $dateThree = DoctorTime::whereUserId($user->id)->whereType('appoint')->whereDays(date('Y-m-d',strtotime('+2 days')))->first();
//        $dateFour = DoctorTime::whereUserId($user->id)->whereType('appoint')->whereDays(date('Y-m-d',strtotime('+3 days')))->first();
//        $dateFire = DoctorTime::whereUserId($user->id)->whereType('appoint')->whereDays(date('Y-m-d',strtotime('+4 days')))->first();
//        $dateSix = DoctorTime::whereUserId($user->id)->whereType('appoint')->whereDays(date('Y-m-d',strtotime('+5 days')))->first();
//        $dateSeven = DoctorTime::whereUserId($user->id)->whereType('appoint')->whereDays(date('Y-m-d',strtotime('+6 days')))->first();

        $dateOne = DoctorWeek::whereUserId($user->id)->whereType('appoint')->whereWeek(Tools::getWeekNum(time()))->first();
        $dateTwo = DoctorWeek::whereUserId($user->id)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+1 days')))->first();
        $dateThree = DoctorWeek::whereUserId($user->id)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+2 days')))->first();
        $dateFour = DoctorWeek::whereUserId($user->id)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+3 days')))->first();
        $dateFire = DoctorWeek::whereUserId($user->id)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+4 days')))->first();
        $dateSix = DoctorWeek::whereUserId($user->id)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+5 days')))->first();
        $dateSeven = DoctorWeek::whereUserId($user->id)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+6 days')))->first();

        $doctor = Doctors::whereUserId($user->id)->first();

        return view('doctors.set-appolitment',[
            'date_one'=>$dateOne,
            'date_two'=>$dateTwo,
            'date_three'=>$dateThree,
            'date_four'=>$dateFour,
            'date_fire'=>$dateFire,
            'date_six'=>$dateSix,
            'date_seven'=>$dateSeven,
            'doctor' => $doctor
        ]);
    }

    public function setFace(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=docUserCenter');
        }

        /** @var User $user */
//        $dateOne = DoctorTime::whereUserId($user->id)->whereType('face')->whereDays(date('Y-m-d',time()))->first();
//        $dateTwo = DoctorTime::whereUserId($user->id)->whereType('face')->whereDays(date('Y-m-d',strtotime('+1 days')))->first();
//        $dateThree = DoctorTime::whereUserId($user->id)->whereType('face')->whereDays(date('Y-m-d',strtotime('+2 days')))->first();
//        $dateFour = DoctorTime::whereUserId($user->id)->whereType('face')->whereDays(date('Y-m-d',strtotime('+3 days')))->first();
//        $dateFire = DoctorTime::whereUserId($user->id)->whereType('face')->whereDays(date('Y-m-d',strtotime('+4 days')))->first();
//        $dateSix = DoctorTime::whereUserId($user->id)->whereType('face')->whereDays(date('Y-m-d',strtotime('+5 days')))->first();
//        $dateSeven = DoctorTime::whereUserId($user->id)->whereType('face')->whereDays(date('Y-m-d',strtotime('+6 days')))->first();
//
//        $dateOneAppoint = DoctorTime::whereUserId($user->id)->whereType('appoint')->whereDays(date('Y-m-d',time()))->first();
//        $dateTwoAppoint = DoctorTime::whereUserId($user->id)->whereType('appoint')->whereDays(date('Y-m-d',strtotime('+1 days')))->first();
//        $dateThreeAppoint = DoctorTime::whereUserId($user->id)->whereType('appoint')->whereDays(date('Y-m-d',strtotime('+2 days')))->first();
//        $dateFourAppoint = DoctorTime::whereUserId($user->id)->whereType('appoint')->whereDays(date('Y-m-d',strtotime('+3 days')))->first();
//        $dateFireAppoint = DoctorTime::whereUserId($user->id)->whereType('appoint')->whereDays(date('Y-m-d',strtotime('+4 days')))->first();
//        $dateSixAppoint = DoctorTime::whereUserId($user->id)->whereType('appoint')->whereDays(date('Y-m-d',strtotime('+5 days')))->first();
//        $dateSevenAppoint = DoctorTime::whereUserId($user->id)->whereType('appoint')->whereDays(date('Y-m-d',strtotime('+6 days')))->first();

        $dateOne   = DoctorWeek::whereUserId($user->id)->whereType('face')->whereWeek(Tools::getWeekNum(time()))->first();
        $dateTwo   = DoctorWeek::whereUserId($user->id)->whereType('face')->whereWeek(Tools::getWeekNum(strtotime('+1 days')))->first();
        $dateThree = DoctorWeek::whereUserId($user->id)->whereType('face')->whereWeek(Tools::getWeekNum(strtotime('+2 days')))->first();
        $dateFour  = DoctorWeek::whereUserId($user->id)->whereType('face')->whereWeek(Tools::getWeekNum(strtotime('+3 days')))->first();
        $dateFire  = DoctorWeek::whereUserId($user->id)->whereType('face')->whereWeek(Tools::getWeekNum(strtotime('+4 days')))->first();
        $dateSix   = DoctorWeek::whereUserId($user->id)->whereType('face')->whereWeek(Tools::getWeekNum(strtotime('+5 days')))->first();
        $dateSeven = DoctorWeek::whereUserId($user->id)->whereType('face')->whereWeek(Tools::getWeekNum(strtotime('+6 days')))->first();

        $dateOneAppoint   = DoctorWeek::whereUserId($user->id)->whereType('appoint')->whereWeek(Tools::getWeekNum(time()))->first();
        $dateTwoAppoint   = DoctorWeek::whereUserId($user->id)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+1 days')))->first();
        $dateThreeAppoint = DoctorWeek::whereUserId($user->id)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+2 days')))->first();
        $dateFourAppoint  = DoctorWeek::whereUserId($user->id)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+3 days')))->first();
        $dateFireAppoint  = DoctorWeek::whereUserId($user->id)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+4 days')))->first();
        $dateSixAppoint   = DoctorWeek::whereUserId($user->id)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+5 days')))->first();
        $dateSevenAppoint = DoctorWeek::whereUserId($user->id)->whereType('appoint')->whereWeek(Tools::getWeekNum(strtotime('+6 days')))->first();


        $doctor = Doctors::whereUserId($user->id)->first();
        return view('doctors.set-face',[
            'date_one'=>$dateOne,
            'date_two'=>$dateTwo,
            'date_three'=>$dateThree,
            'date_four'=>$dateFour,
            'date_fire'=>$dateFire,
            'date_six'=>$dateSix,
            'date_seven'=>$dateSeven,
            'date_one_appoint'=>$dateOneAppoint,
            'date_two_appoint'=>$dateTwoAppoint,
            'date_three_appoint'=>$dateThreeAppoint,
            'date_four_appoint'=>$dateFourAppoint,
            'date_fire_appoint'=>$dateFireAppoint,
            'date_six_appoint'=>$dateSixAppoint,
            'date_seven_appoint'=>$dateSevenAppoint,
            'doctor' => $doctor
        ]);
    }

    public function myQuestions(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=usercenter');
        }

        /** @var User $user */

        $questions = Questions::whereDoctorId($user->id)->get();

        return view('doctors.my-questions',['questions'=>$questions]);
    }

    public function answerQuestion(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=doctordetail');
        }

        $qid = Input::get('q_id');

        /** @var Questions $question */
        $question = Questions::whereId($qid)->first();

        if(!$question)
            throw new NotFoundException(NotFoundException::DataNotFound);

        $question->read_num = $question->read_num + 1;
        $question->save();

            /** @var User $user */

        $userInfo = UserInfo::whereUserId($question->user_id)->first();

        $doctor = Doctors::whereUserId($user->id)->first();

        return view('doctors.answer-question',['user'=>$user,'userinfo'=>$userInfo,'doctor'=>$doctor,'question'=>$question]);
    }

    public function myAnswer(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=usercenter');
        }

        /** @var User $user */

        $questionId = Input::get('q_id');

        /** @var Questions $thatQuestion */
        $thatQuestion = Questions::whereId($questionId)->first();

        if(!$thatQuestion)
            throw new NotFoundException(NotFoundException::DataNotFound);

        $thatQuestion->read_num = $thatQuestion->read_num + 1;
        $thatQuestion->save();

        /** @var Doctors $doctor */
        $doctor = Doctors::whereUserId($thatQuestion->doctor_id)->first();

        $hospital = Hospital::whereId($doctor->hospital_id)->first();

        return view('doctors.my-answer',['question'=>$thatQuestion,'doctor'=>$doctor,'hospital'=>$hospital]);
    }

    public function myQrcode(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=usercenter');
        }

        /** @var User $user */

        /** @var Doctors $doctor */
        $doctor = Doctors::whereUserId($user->id)->first();

        $hospital = Hospital::whereId($doctor->hospital_id)->first();

        return view('doctors.my-qrcode',['doctor'=>$doctor,'hospital'=>$hospital]);
    }

    public function orderList(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin'));
        }

        $modelid = !is_null(Input::get('model')) ? Input::get('model') : 0;

        /** @var User $user */
        if((int)$user->role !== 1)
            return redirect(route('Api.Auth.weixinLogin'));

        $orders = null;
        switch((int)$modelid){
            case 0:
                $orders = Orders::whereDoctorId($user->id)->whereIspay(1)->orderBy('created_at','desc')->get();
                break;
            case 1:
                $orders = Orders::whereDoctorId($user->id)->whereIspay(1)->whereType('appoint')->orderBy('created_at','desc')->get();
                break;
            case 2:
                $orders = Orders::whereDoctorId($user->id)->whereIspay(1)->whereType('face')->orderBy('created_at','desc')->get();
                break;
            case 3:
                $orders = Orders::whereDoctorId($user->id)->whereIspay(1)->whereType('package')->orderBy('created_at','desc')->get();
                break;
        }

        foreach($orders as $order){
            /** @var Orders $order */
            $hospital = '';
            /** @var Hospital $thatHospital */
            $thatHospital = Hospital::whereId($order->hospital_id)->first();

            if($thatHospital)
                $hospital = $thatHospital->name;


            if($order->type == 'appoint'){
                /** @var UserInfo $thatUserInfo */
                $thatUserInfo = UserInfo::whereUserId($order->user_id)->first();
                if($thatUserInfo){
                    $order->img_id   = $thatUserInfo->portrait_id;
                    $order->title    = $thatUserInfo->realname."【门诊】";
                    $order->hospital = $hospital;
                }else{
                    $order->img_id = 0;
                    $order->title = "该用户已被删除";
                }

            }elseif($order->type == 'face'){
                /** @var UserInfo $thatUserInfo */
                $thatUserInfo = UserInfo::whereUserId($order->user_id)->first();
                if($thatUserInfo){
                    $order->img_id = $thatUserInfo->portrait_id;
                    $order->title = $thatUserInfo->realname."【面诊】";
                }else{
                    $order->img_id = 0;
                    $order->title = "该用户已被删除";
                }
            }
        }

        return view('doctors.order-list',['orders'=>$orders,'model'=>$modelid,'page'=>'usercenter']);
    }

    public function myPatients(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=doctordetail');
        }

        /** @var User $user */

        $myFollowPatientIds = UserXDoctor::whereDoctorId($user->id)->get();

        $docIds = array();
        foreach($myFollowPatientIds as $myFollowDocId){
            array_push($docIds,$myFollowDocId->user_id);
        }

        $allPatients = UserInfo::whereIn('user_id',$docIds)->orderBy('created_at','desc')->get();

        return view('doctors.my-patients',['patients'=>$allPatients]);
    }

    public function referral(Request $request,Guard $guard){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=doctordetail');
        }

        /** @var User $user */

        $userId = $request->get('id');

        /** @var User $thatUser */
        $thatUser = User::whereId($userId)->first();
        if(!$thatUser){
            echo "user_not_found";die;
        }

        $thatUserInfo = $thatUser->userInfo;

        /** @var Doctors $thatDoctor */
        $thatDoctor = Doctors::whereUserId($user->id)->first();
        if(!$thatDoctor){
            echo "user_not_found";die;
        }

        /** @var Hospital $thatHospital */
        $thatHospital = Hospital::whereId($thatDoctor->hospital_id)->first();

        $allHospital = Hospital::all();

        return view('doctors.referral',[
            'that_user'     =>$thatUser,
            'that_userinfo' =>$thatUserInfo,
            'hospital'      =>$thatHospital,
            'all_hospital'  =>$allHospital
        ]);
    }

    public function hospitalList(){
        $allHospital = Hospital::whereNotNull('telephone')->orderBy('created_at','desc')->get();

        return view('doctors.hospital-list',['hospitals'=>$allHospital]);
    }

    public function confirmReferral(Request $request){

        $referralId = $request->get('referral_id');

        /** @var Referral $thatReferral */
        $thatReferral = Referral::whereId($referralId)->first();

        if(!$thatReferral){
            echo "转诊信息不存在";die;
        }

        $thatPatientInfo = UserInfo::whereUserId($thatReferral->user_id)->first();
        $thatDoctor = Doctors::whereUserId($thatReferral->d_user_id)->first();
        if($thatDoctor){
            $thatHospital = Hospital::whereId($thatDoctor->hospital_id)->first();
            if($thatHospital){
                $thatDoctor->hospital = $thatHospital->name;
            }else{
                $thatDoctor->hospital = '';
            }
        }else{
            echo "发起转诊医生不存在";die;
        }

        return view('doctors.confirm-referral',['patient'=>$thatPatientInfo,'doctor'=>$thatDoctor,'referral'=>$thatReferral]);
    }

    public function patientList(Request $request,Guard $guard){
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.weixinLogin').'?state=doctordetail');
        }

        /** @var User $user */

        if($user->role == 0){
            echo '只有医生才可以访问哦！';die;
        }

        /** @var Doctors $thatDoctor */
        $thatDoctor = Doctors::whereUserId($user->id)->first();

        if(!$thatDoctor)
            return response()->json(['level'=>'error','message'=>'用户未找到']);

        $keyword = $request->get('keyword');

        $query = DB::table('user_info')
                 ->join('users', 'users.id', '=', 'user_info.user_id')
                 ->join('user_x_doctor', 'user_x_doctor.user_id', '=', 'user_info.user_id')
                 ->where('users.role','=',0)
                 ->where('user_x_doctor.doctor_id','=',$thatDoctor->user_id)
                 ->whereNull('user_info.deleted_at');

        if(!is_null($keyword)){
            $query->where(function($q) use ($keyword){
                $q->where('user_info.realname','like','%'.$keyword.'%');
            });
        }

        $allPatients = $query->orderBy('user_info.created_at','desc')->get();

        return view('doctors.patient-list',['patients'=>$allPatients,'keyword'=>$keyword,"doctor"=>$thatDoctor]);
    }
}